package objectstream;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.junit.jupiter.api.Test;

import serializable.Person;

public class ObjectStream {
	@Test
	public void writeBasicType(){
		//1.创建一个文件输出字节流，对象输出字节流
		try(FileOutputStream fos = new FileOutputStream("type.txt");
			ObjectOutputStream oos = new ObjectOutputStream(fos);){
			//2.往外按数据类型写,写出去一定引用类型
			oos.writeInt(100);
			oos.writeBoolean(false);
			oos.writeChar('A');
			oos.writeDouble(1.1);
			oos.writeUTF("hello");
			//写自定义的对象
			//java.io.NotSerializableException 没有被序列化
			oos.writeObject(new Person(1,"张三",'男'));
			
			//3.刷新
			oos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void readBasicType(){
		//1.创建一个文件输入字节流，对象输入字节流
		try(FileInputStream fos = new FileInputStream("type.txt");
			ObjectInputStream oos = new ObjectInputStream(fos);){
			//2.往外按数据类型读,读取的顺序一定要和写的顺序一致
			System.out.println(oos.readInt());
			System.out.println(oos.readBoolean());
			System.out.println(oos.readChar());
			System.out.println(oos.readDouble());
			System.out.println(oos.readUTF());
			System.out.println(oos.readObject());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
